{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "## Use the GLM-4 model combined with the knowledge base function of Zhipu AI to answer questions\n",
    "\n",
    "**This tutorial is available in English and is attached below the Chinese explanation**\n",
    "\n",
    "本代码中，我将使用在 [智谱大模型开放平台](https://open.bigmodel.cn/knowledge) 可视化构建的知识库作为参考，使用智谱自带的知识库调用插件，结合我上传的知识库回答问题。\n",
    "本代码仅包含使用代码进行调用，关于如何创建知识库，你可以访问这里：[智谱知识库创建方法](https://open.bigmodel.cn/appcenter/myapp)。\n",
    "\n",
    "In this cookbook, I will use the knowledge base visually constructed on [ZhipuAI LLM Open Platform](https://open.bigmodel.cn/knowledge) as a reference, use the knowledge base call plug-in that comes with Zhipu, and combine it with my Upload the knowledge base to answer questions.\n",
    "This code only includes calls using code. For information on how to create a knowledge base, you can visit here: [How to create a knowledge base](https://open.bigmodel.cn/appcenter/myapp).\n"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "390920eee68ee290"
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 1. Import the ZhipuAI package and set the API key\n",
    "\n",
    "首先，需要安装智谱AI 的 Python SDK，然后设置 API key。\n",
    "\n",
    "First, you need to install the ZhipuAI Python SDK, and then set the API key."
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "67d1dcfa723f2b58"
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "import os\n",
    "from zhipuai import ZhipuAI\n",
    "\n",
    "os.environ[\"ZHIPUAI_API_KEY\"] = \"your api key here\"\n",
    "client = ZhipuAI()\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-02-05T06:24:36.721272Z",
     "start_time": "2024-02-05T06:24:36.485892Z"
    }
   },
   "id": "4920299b115b2638"
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 2. Use the GLM-4 model combined with the knowledge base function of Zhipu AI to answer questions\n",
    "\n",
    "接着，设置知识库的 ID，这个 ID 是在创建知识库时生成的。\n",
    "同时，你应该设置 prompt_template，这是一个模板，用于告诉模型如何使用知识库来回答问题。\n",
    "这样，我们就能请求模型根据知识库回答我们的问题了\n",
    "\n",
    "Next, set the ID of the knowledge base, which is generated when the knowledge base is created.\n",
    "At the same time, you should set prompt_template, which is a template that tells the model how to use the knowledge base to answer questions.\n",
    "In this way, we can request the model to answer our questions based on the knowledge base."
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "369d15cd60ffe7fe"
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [],
   "source": [
    "prompt_template = \"\"\"\n",
    "从文档\n",
    "{{knowledge}}\n",
    "中找问题\n",
    "{{question}}\n",
    "的答案，\n",
    "找到答案就仅使用文档语句回答，找不到答案就用自身知识回答并告诉用户该信息不是来自文档。\n",
    "不要复述问题，直接开始回答。\n",
    "\"\"\"\n",
    "knowledge_id = 1748261416734965760 ## my knowledge base id\n",
    "response = client.chat.completions.create(\n",
    "    model=\"glm-4\", \n",
    "    messages=[\n",
    "        {\"role\": \"user\", \"content\": \"大数据专业未来的升学情况\"},\n",
    "    ],\n",
    "    tools=[\n",
    "        {\n",
    "            \"type\": \"retrieval\",\n",
    "            \"retrieval\": {\n",
    "                \"knowledge_id\": knowledge_id,\n",
    "                \"prompt_template\": prompt_template,\n",
    "            }\n",
    "        }\n",
    "    ],\n",
    "    stream=False,\n",
    ")"
   ],
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-02-05T06:32:06.360962Z",
     "start_time": "2024-02-05T06:32:01.283105Z"
    }
   },
   "id": "initial_id"
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 3. Print the response\n",
    "\n",
    "通过打印的回答，我们看到，模型使用了知识库中的信息回答了我们的问题。而不是使用模型自带的知识，这种调用方式比自己创建和管理知识库更加方便。大大降低了学习成本。\n",
    "\n",
    "By printing the answer, we see that the model used the information in the knowledge base to answer our question. Instead of using the knowledge base built into the model, this method of calling is more convenient than creating and managing the knowledge base by yourself. Greatly reduces the learning cost."
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "ed50fa0606ec8157"
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "data": {
      "text/plain": "Completion(model='glm-4', created=1707114726, choices=[CompletionChoice(index=0, finish_reason='stop', message=CompletionMessage(content='根据文档内容，大数据专业未来的升学情况可以概括为：学生可以申请全球顶级院校的相关专业，如人工智能、计算机、大数据等。在2023年，该专业本科毕业生中42%申请到全球排名前10的大学，96%申请到全球排名前100的大学。此外，该专业有三位学生申请到了哈佛大学，成为全校唯一一个有此成就的专业。最终升学数据以西浦就业中心发布的《2023届毕业生就业质量发展报告》为准。', role='assistant', tool_calls=None))], request_id='8356082075303189161', id='8356082075303189161', usage=CompletionUsage(prompt_tokens=1888, completion_tokens=105, total_tokens=1993))"
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-02-05T06:32:06.366878Z",
     "start_time": "2024-02-05T06:32:06.362606Z"
    }
   },
   "id": "8001646eb7ca6bfd"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
